package com.ak.demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
//                .usernameParameter("username123")
//                .passwordParameter("password123")
                .loginPage("/myLoginController") // 一定要和 Controller 中 返回 myLogin页面 一致，
                .loginProcessingUrl("/login")// 必须和表单提交 action 的名字 一样的，提交 username 和password
                .successForwardUrl("/toSuccess");// 这个是 登录成功后返回的界面
//        .successHandler(new AuthenticationSuccessHandler() {
//            @Override
//            public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//                httpServletResponse.sendRedirect("https://www.baidu.com");
//            }
//        }).failureHandler(new ForwardAuthenticationFailureHandler("/toFail"));


        http.authorizeRequests()
                .antMatchers("/myLoginController").permitAll()// 放行myLoginController
//                .antMatchers("/Vip1").hasAuthority("vip1")
//                .antMatchers("/Vip2").hasAuthority("vip2")
//                .antMatchers("/**/*.png").permitAll()
//                .antMatchers("/toRole").hasRole("abc")
                //.antMatchers("toRole").access("hasRole('abc')")
                //.antMatchers("/toRole").hasIpAddress("127.0.0.1")
                .anyRequest().authenticated();
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
